import axios from 'axios';
import { ElMessage } from 'element-plus';
import router from '@/router';
import { useApp } from '@/pinia/modules/app';

const service = axios.create({
  baseURL: 'http://localhost:9090',
  timeout: 10000,
  withCredentials: true,
});


// 拦截请求
service.interceptors.request.use(
  config => {
    // const { authorization } = useApp();
    // if (authorization) {
    //   config.headers.Authorization = `Bearer ${authorization.token}`;
    // }
    // return config;
    const token=localStorage.getItem("token")
    if(typeof token == "undefined" || token == null || token == ""){
      return config;
    }else{
      config.headers['token']=token;
    }
    return config;
    
  },
  error => {
    // console.log(error);
    return Promise.reject(error);
  }
);

// 拦截响应
service.interceptors.response.use(
  // 响应成功进入第1个函数，该函数的参数是响应对象
  response => {
    if(response.data.code=='401'){
      ElMessage.error(response.data.msg);
      localStorage.removeItem("token")
      router.push('/login')
    }else if(response.data.code=='500'){
      ElMessage.error(response.data.msg);
    }else{
      return response.data;
    }
  },
  // 响应失败进入第2个函数，该函数的参数是错误对象
  async error => {

    // console.dir(error) // 可在此进行错误上报
    ElMessage.closeAll();
    try {
      ElMessage.error(error.response.data.msg);
    } catch (err) {
      ElMessage.error(error.message);
    }

    return Promise.reject(error);
  }
);

export default service;
